package com.lxx.redisdemo.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lxx.redisdemo.Utils.RedisUtils;
import com.lxx.redisdemo.mapper.UserMapper;
import com.lxx.redisdemo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisUtils redisUtils;

    public User queryUser(String name) throws Exception {

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        User user = new User();
        wrapper.eq("name", name);
        //先判断redis中是否存在数据
        if (!StringUtils.isEmpty(redisUtils.get(name))) {
            //redis中有直接返回
            user.setName(name);
            user.setAge((int) redisUtils.get(name));
            return user;
        }

        //不存在就先查数据库
         user = userMapper.selectOne(wrapper);
        //查询出的结果先放redis一份
        redisUtils.set(user.getName(), user.getAge());
        //返回
        return user;

    }

}
